# 文件的读取
try:
    f = open("../file/huhx1.txt", "r")
    print(f.read())
finally:
    if f:
        f.close()

# 调用read()会一次性读取文件的全部内容
with open("../file/log.txt", "r") as f:
    print(f.read())

with open("../file/huhx2.txt", "r", encoding="utf-8") as f:
    for line in f.readlines():
        print(line.strip())

# 二进制的读取
with open("../file/huhx.png", "rb") as f:
    print(f.read())

# 写文件
with open("../file/log.txt", "a") as f:
    f.write("hello world, and I love you.")

# stringIO：在内存中读写str。
from io import StringIO, BytesIO
f = StringIO("hello world.\nI love you.\nmy name is huhx.")
while True:
    s = f.readline()
    if s == "":
        break
    print(s.strip())

# BytesIO: 内存中读写bytes
f = BytesIO("中文".encode("utf-8"))
print(f.read()) # b'\xe4\xb8\xad\xe6\x96\x87'
print(f.getvalue()) # b'\xe4\xb8\xad\xe6\x96\x87'

# 操作文件和目录
import os
# uname()函数在Windows上不提供
print(os.name, os.environ)

# 修改文件名称，删除文件
# os.rename("../file/log.txt", "../file/log1.txt")
# os.rename("../file/huhx.doc", "../file/liuling.txt")
# os.remove("../file/liuling.txt")

# dumps是返回string，dump是写进文件中。
import pickle
d = dict(name="huhx", age=24, score=99)
dump_data = pickle.dumps(d)
print(dump_data)

d = pickle.loads(dump_data)
print(d) # {'age': 24, 'score': 99, 'name': 'huhx'}

# json
import json
json_data = json.dumps(d)
print(json_data) # {"name": "huhx", "age": 24, "score": 99}
print(json.loads(json_data)) # {'score': 99, 'age': 24, 'name': 'huhx'}

# __dict__的测试
class Human(object):
    __slots__ = "sex, name, age, addr"
    def __init__(self):
        self.name = "huhx"
        self.age = 34
        self.addr = "wuhan"
human = Human()
print(human.__dict__)
